let db = require("../db/db")
let ddl_handler = require("./custom/ddl_handler")

ddl_handler.set_db(db);

let find_fields = function (controls) {
	let fields = [];
	for (let c of controls) {
		if (c.type == "fieldSet") {
			fields = fields.concat(find_fields(c.body));
		}
		else {
			fields.push(c);
		}
	}
	return fields;
}

let handle = async function (action, data, login_info, req, res) {
	switch (action) {
		case "quickbuild":
			//console.log(data);
			//新建数据模型，需要同时创建CRUD相关
			if (data.datamodel_source_type == "新建") {
				let trans = await db.transaction(multi = true);
				try {
					//检查表名是否存在，列名是否有重复，有空列名
					let sql="SELECT table_name as ct FROM information_schema.TABLES WHERE table_schema in (select database()) and table_name =?";
					let result=await trans.query(sql, [data.tablename]);
					if(result.rows.length>0){
						throw {name:"检查提交数据错误", message:"已经存在表: "+data.tablename};
					}
					if(data.fields.length==0){
						throw {name:"检查提交数据错误", message:"没有设置字段。"};
					}
					for (let field of data.fields) {
						let find=data.fields.filter(f=>f.field_name==field.field_name);
						if(find && find.length>1){
							throw {name:"检查提交数据错误", message:"重复的字段名: "+field.field_name};
						}
						if(!field.field_name){
							throw {name:"检查提交数据错误", message:"字段名为空: "+let.name};
						}
					}
					//创建逻辑
					let config_fields = [];
					let property_columns = [];
					let fields = find_fields(data.controls_new);
					for (let i in fields) {
						let f = fields[i];
						let type = "varchar";
						if (["date", "datetime"].includes(f.type)) {
							type = f.type;
						}
						let config_field = {
							"id": i + 1,
							"name": f.field_name,
							"label": f.name,
							"required": f.required,
							"length": f.field_length,
							"type": type
						}
						let property_column = {
							"name": f.field_name,
							"label": f.name,
							"searchable": true,
							"sortable": true,
							"quickedit": true
						}
						if (["number", "textarea", "date", "datetime", "switch"].includes(f.type)) {
							property_column.type = f.type;
						}
						else if (f.type == "file") {
							config_field.length = 100;
							property_column.type = "file";
						}
						else if (f.type == "image") {
							config_field.length = 100;
							property_column.type = "image";
						}
						else if (f.type == "radios") {
							property_column.type = "radios";
							property_column.options = f.options;
						}
						else if (f.type == "checkboxes") {
							property_column.type = "checkboxes";
							property_column.options = f.options;
						}
						else if (f.type == "select") {
							property_column.type = "select";
							config_field.select = { group: f.group_name };
						}
						else if (f.type == "related") {
							config_field.related = {
								"datamodel": f.related_datamodel,
								"model_table_name": f.related_table,
								"that_field": f.that_field,
								"that_label_field": f.that_label_field,
								"label": f.name
							}
							if (f.select_type == "select") {
								property_column.related = {
									"select_type": "select",
									"tree_select": [
										{
											"label": f.name,
											"label_field": f.that_label_field,
											"table_name": f.related_table,
											"this_field": f.that_field
										}
									]
								}
							}
							else if (f.select_type == "picker") {
								property_column.related = {
									"select_type": "picker",
									"datamodel": f.related_datamodel
								}
							}
						}
						config_fields.push(config_field)
						property_columns.push(property_column)
					}
					//数据模型
					let datamodel_params = {
						module: data.module,
						name: data.model_name,
						tablename: data.tablename,
						desc: data.desc,
						config: JSON.stringify({
							fields: config_fields
						}),
						create_user: login_info.user_id
					}
					sql = "insert into sys_datamodel set ?";
					let r = await trans.add(sql, datamodel_params);
					let model_id = r.results.insertId;
					//数据权限表
					result = await ddl_handler.add_data_funcs(model_id, login_info, req, res);
					let data_func_read_id = result.results[0].insertId;
					let data_func_add_id = result.results[1].insertId;
					let data_func_update_id = result.results[2].insertId;
					let data_func_del_id = result.results[3].insertId;
					//CRUD页面、表单页面
					let crud_page_params = {
						module: data.module,
						name: data.model_name + "管理",
						page_type_id: 1,
						desc: data.desc,
						property: JSON.stringify({
							"datamodel": model_id,
							"model_table_name": data.tablename,
							"columns": property_columns
						}),
						create_user: login_info.user_id
					}
					let form_page_params = {
						module: data.module,
						name: data.model_name + "表单",
						page_type_id: 11,
						desc: data.desc,
						property: JSON.stringify({
							datamodel: model_id,
							tablename: data.tablename,
							page: {
								"title": data.title,
								"subtitle": data.subtitle,
								"controls": data.controls_new,
								"description": data.description
							}
						}),
						create_user: login_info.user_id
					}
					sql = "insert into sys_page set ?; insert into sys_page set ?;";
					r = await trans.add(sql, [crud_page_params, form_page_params]);
					//功能权限(CRUD、FORM)
					let crud_page_id = r.results[0].insertId;
					let form_page_id = r.results[1].insertId;
					result = await ddl_handler.add_functions(crud_page_id, 1, login_info, req, res);
					let crud_func_id = result.results.insertId ? result.results.insertId : result.results[0].insertId;
					result = await ddl_handler.add_functions(form_page_id, 11, login_info, req, res);
					let form_func_id = result.results.insertId ? result.results.insertId : result.results[0].insertId;
					//赋权(CRUD、FORM、DATAMODEL)
					sql = "";
					let role_params = [];
					for (let role_id of data.roles.split(",")) {
						sql += "insert into sys_role_func_r set ? ; insert into sys_role_func_r set ? ; \
								insert into sys_role_data_func_r set ? ; insert into sys_role_data_func_r set ? ;\
								insert into sys_role_data_func_r set ? ; insert into sys_role_data_func_r set ? ;";
						role_params.push({
							role_id: role_id,
							func_id: crud_func_id
						});
						role_params.push({
							role_id: role_id,
							func_id: form_func_id
						});
						role_params.push({
							role_id: role_id,
							data_func_id: data_func_read_id
						});
						role_params.push({
							role_id: role_id,
							data_func_id: data_func_add_id
						});
						role_params.push({
							role_id: role_id,
							data_func_id: data_func_update_id
						});
						role_params.push({
							role_id: role_id,
							data_func_id: data_func_del_id
						});
					}
					r = await trans.add(sql, role_params);
					//菜单(CRUD、FORM)
					let form_menu_params = {
						name: "新建" + data.model_name,
						icon: "fa-paper-plane-o",
						parent_id: data.parent_menu,
						page_id: form_page_id,
						create_user: login_info.user_id
					}
					let crud_menu_params = {
						name: data.model_name,
						icon: "fa-paper-plane",
						parent_id: data.parent_menu,
						page_id: crud_page_id,
						create_user: login_info.user_id
					}
					sql = "insert into sys_menu set ?; insert into sys_menu set ?;";
					r = await trans.add(sql, [crud_menu_params, form_menu_params]);
					let form_menu_id = r.results[0].insertId;
					let crud_menu_id = r.results[1].insertId;
					//提交全部事务
					await trans.commit();
					//数据库表最后加，因为ddl不能rollback
					result = await ddl_handler.ddl_add_table(data.tablename, JSON.parse(datamodel_params.config));
					console.log("CRUD quick built successfully!");
					return ({ model_id: model_id, crud_page_id: crud_page_id, form_page_id: form_page_id, crud_menu_id: crud_menu_id, form_menu_id: form_menu_id });
				}
				catch (err) {
					trans.rollback();
					throw (err);
				}
			}
			//现有数据模型，只生成表单相关
			else {
				let model_id = data.old_datamodel;
				let trans = db.transaction(multi = true);
				try {
					//表单页面
					let form_page_params = {
						module: data.module,
						name: data.model_name + "表单",
						page_type_id: 11,
						desc: data.desc,
						property: JSON.stringify({
							datamodel: model_id,
							tablename: data.tablename,
							page: {
								"title": data.title,
								"subtitle": data.subtitle,
								"controls": data.controls_old,
								"description": data.description
							}
						}),
						create_user: login_info.user_id
					}
					let sql = "insert into sys_page set ?";
					let r = await trans.add(sql, form_page_params);
					//功能权限(FORM)
					let form_page_id = r.results.insertId;
					let result = await ddl_handler.add_functions(form_page_id, 11, login_info, req, res);
					let form_func_id = result.results.insertId ? result.results.insertId : result.results[0].insertId;
					//赋权(CRUD、FORM、DATAMODEL)
					sql = "";
					let role_params = [];
					for (let role_id of data.roles.split(",")) {
						sql += "insert into sys_role_func_r set ?;";
						role_params.push({
							role_id: role_id,
							func_id: form_func_id
						});
					}
					r = await trans.add(sql, role_params);
					//菜单(FORM)
					let form_menu_params = {
						name: "新建" + data.model_name,
						icon: "fa-paper-plane-o",
						parent_id: data.parent_menu,
						page_id: form_page_id,
						create_user: login_info.user_id
					}
					sql = "insert into sys_menu set ?";
					r = await trans.add(sql, form_menu_params);
					let form_menu_id = r.results.insertId;
					//提交全部事务
					await trans.commit();
					console.log("CRUD quick built successfully!");
					return ({ model_id: model_id, form_page_id: form_page_id, form_menu_id: form_menu_id });
				}
				catch (err) {
					trans.rollback();
					throw (err);
				}
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };